package com.example.authsystem.service.impl;

import com.example.authsystem.dto.*;
import com.example.authsystem.entity.User;
import com.example.authsystem.repository.UserRepository;
import com.example.authsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository; // 假设你已定义该接口

    @Override
    @Operation(summary = "用户注册", description = "创建新用户账户")
    public User registerUser(RegisterRequest registerRequest) {
        log.info("注册用户: {}", registerRequest.getUsername());

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPasswordHash(registerRequest.getPassword()); // 假设直接存储明文密码（实际应加密）
        user.setStatus("ACTIVE");
        user.setCreateTime(LocalDateTime.now());

        return userRepository.save(user);
    }

    @Override
    @Operation(summary = "用户登录", description = "验证用户凭据并返回JWT令牌")
    public JwtResponse loginUser(LoginRequest loginRequest, String deviceId, String location) {
        String rawPhone = loginRequest.getPhone();
        String cleanedPhone = null;

        // 【新增】预处理：清洗手机号（仅保留数字）
        if (rawPhone != null) {
            cleanedPhone = rawPhone.replaceAll("[^\\d]", ""); // 移除所有非数字字符
            if (cleanedPhone.isEmpty()) {
                cleanedPhone = null; // 视为空
            }
        }

        // 校验清洗后的手机号格式（如果存在）
        if (cleanedPhone != null && !cleanedPhone.matches("^1[3-9]\\d{9}$")) {
            throw new IllegalArgumentException("手机号格式不正确，应为11位数字，以1开头");
        }

        log.info("用户登录: {}, 设备: {}, 位置: {}", loginRequest.getUsername(), deviceId, location);

        // 后续逻辑使用 cleanedPhone 而不是 rawPhone 查库
        User user = userRepository.findByUsernameIgnoreCase(loginRequest.getUsername())
                .or(() -> userRepository.findByEmailIgnoreCase(loginRequest.getUsername()))
                .or(() -> rawPhone != null ? userRepository.findByPhone(rawPhone) : Optional.empty())
                .orElseThrow(() -> new IllegalArgumentException("用户名/邮箱/手机号或密码错误"));

        if (user == null || !user.getPasswordHash().equals(loginRequest.getPassword())) {
            throw new IllegalArgumentException("用户名/邮箱/手机号或密码错误");
        }

        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userRepository.save(user);

        return JwtResponse.builder()
                .accessToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.example_" + loginRequest.getUsername())
                .refreshToken("refresh_token_" + System.currentTimeMillis())
                .tokenType("Bearer")
                .expiresIn(3600L)
                .build();
    }

    @Override
    @Operation(summary = "刷新令牌", description = "使用刷新令牌获取新的访问令牌")
    public String refreshToken(String refreshToken) {
        log.info("刷新令牌: {}", refreshToken.substring(0, Math.min(10, refreshToken.length())));
        return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.new_access_token";
    }

    @Override
    @Operation(summary = "获取用户列表", description = "分页查询用户列表")
    public UserListResponse getUserList(int page, int size, String keyword) {
        log.info("获取用户列表: page={}, size={}, keyword={}", page, size, keyword);
        return UserListResponse.builder()
                .users(Arrays.asList(
                        UserProfileDto.builder().id(1L).username("admin").email("admin@example.com").build(),
                        UserProfileDto.builder().id(2L).username("user1").email("user1@example.com").build()
                ))
                .total(2L).page(page).size(size).build();
    }

    @Override
    @Operation(summary = "获取用户详情", description = "根据ID获取用户信息")
    public UserProfileDto getUserProfile(Long userId) {
        log.info("获取用户详情: {}", userId);
        return UserProfileDto.builder()
                .id(userId).username("user" + userId).email("user" + userId + "@example.com")
                .realName("用户" + userId).phone("1380000" + String.format("%04d", userId))
                .createdAt(LocalDateTime.now().minusDays(userId)).build();
    }

    @Override
    @Operation(summary = "更新用户", description = "更新用户基本信息")
    public UserProfileDto updateUserProfile(Long userId, UserProfileDto userDto) {
        log.info("更新用户: {}", userId);
        userDto.setId(userId);
        userDto.setUpdatedAt(LocalDateTime.now());
        return userDto;
    }

    @Override
    @Operation(summary = "删除用户", description = "软删除用户")
    public void deleteUser(Long userId) {
        log.info("删除用户: {}", userId);
        // 简化实现，仅记录日志
    }
}
